package org.boun.swe.ARCEONE.Utility;

import java.util.Timer;
import java.util.TimerTask;

import org.boun.swe.ARCEONE.Static.Constants;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class MapViewWithLongPress extends MapView {
	private GeoPoint lastMapCenter;
	private Timer longPressTimer = new Timer();
	private MapViewWithLongPress.OnLongPressListener longPressListener;
	
	public interface OnLongPressListener {
		public void onLongPress(MapView view, GeoPoint longPressLocation);
	}
 
	public MapViewWithLongPress(Context context, String apiKey) {
		super(context, apiKey);
	}

	public MapViewWithLongPress(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MapViewWithLongPress(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void setOnLongPressListener(MapViewWithLongPress.OnLongPressListener listener) {
		longPressListener = listener;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		handleLongPress(event);
		return super.onTouchEvent(event);
	}

	private void handleLongPress(final MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			longPressTimer = new Timer();
			longPressTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					GeoPoint longPressLocation = getProjection().fromPixels((int)event.getX(), (int)event.getY());
					longPressListener.onLongPress(MapViewWithLongPress.this, longPressLocation);
				}
			}, Constants.MAPVIEW_LONGPRESS_THRESHOLD);
			lastMapCenter = getMapCenter();
		}
     
		if (event.getAction() == MotionEvent.ACTION_MOVE) {
			if (!getMapCenter().equals(lastMapCenter))
				longPressTimer.cancel();
			lastMapCenter = getMapCenter();
		}
     
		if (event.getAction() == MotionEvent.ACTION_UP)
			longPressTimer.cancel();

        if (event.getPointerCount() > 1)
            longPressTimer.cancel();
	}
}